package org.jeecg.modules.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;

import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Description: 支付宝支付
 **/

@Component
@Slf4j
public class AliPayKit {

    // 应用域名
    private static String domain;

    @Value("${application.domain}")
    public void setDomain(String domain) {
        AliPayKit.domain = domain;
    }

    // 应用id
    private static String appId;

    @Value("${alipay.appId}")
    public void setAppId(String appId) {
        AliPayKit.appId = appId;
    }

    // 商户私钥
    private static String privateKey;

    @Value("${alipay.merchantPrivateKey}")
    public void setPrivateKey(String privateKey) {
        AliPayKit.privateKey = privateKey;
    }

    // 支付宝公钥
    private static String publicKey;

    @Value("${alipay.alipayPublicKey}")
    public void setPublicKey(String publicKey) {
        AliPayKit.publicKey = publicKey;
    }

    // 支付网关
    private static String gatewayUrl;

    @Value("${alipay.gatewayUrl}")
    public void setGatewayUrl(String gatewayUrl) {
        AliPayKit.gatewayUrl = gatewayUrl;
    }

    // 回调地址
    private static String notifyUrl;

    @Value("${alipay.notifyUrl.default}")
    public void setNotifyUrl(String notifyUrl) {
        AliPayKit.notifyUrl = notifyUrl;
    }

    // 格式
    private static final String format = "JSON";

    // 编码
    public static final String charset = "utf-8";

    // 签名类型
    public static final String signType = "RSA2";


    /**
     * 调用支付
     */
    public static Map<String, String> pay(Map<String, String> params) {
        System.out.println("-------------------->"+params);

        //封装支付入参
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

        model.setBody(params.get("body"));
        model.setSubject(params.get("subject"));
        model.setOutTradeNo(params.get("outTradeNo"));
        model.setTimeoutExpress("90m");
        model.setTotalAmount(params.get("totalAmount"));
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        //支付宝回调接口，支付完成时回调此接口通知支付成功还是失败的消息
        request.setNotifyUrl(domain + params.get("notifyUrl"));

        System.out.println("------回调地址------->"+domain + params.get("notifyUrl"));

        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println("----------入参-----");
            Map<String, String> map = new HashMap<String,String>();
//            log.warn("alipay-"+response.getBody());
            map.put("code","1");
            map.put("message","发起支付");
            map.put("data", response.getBody()); //就是orderString 可以直接给客户端请求，无需再做处理。
            System.out.println("----------完成-----");
            return map;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean buyVipByAlipay(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map < String , String >   params   =   new   HashMap < String , String > ();
        Map   requestParams   =   request . getParameterMap ();
        for  ( Iterator   iter   =   requestParams . keySet (). iterator ();  iter . hasNext ();) {
            String   name   =  ( String )  iter . next ();
            String []  values   =  ( String [])  requestParams . get ( name );
            String   valueStr   =   "" ;
            for  ( int   i   =   0 ;  i   <   values . length ;  i ++ ) {
                valueStr   =  ( i   ==   values . length   -   1 )  ?   valueStr   +   values [ i ]
                        :  valueStr   +   values [ i ]  +   "," ;
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params . put ( name ,  valueStr );
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCertCheckV1(Map<String, String> params, String publicKeyCertPath, String charset,String signType)
        boolean   flag=false;
        try {
               flag   =   AlipaySignature . rsaCertCheckV1 ( params ,  publicKey ,  charset , "RSA2" );
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return flag;

    }

    // 支付宝退款
    public static AlipayTradeRefundResponse refund(Map<String, String> params) {

        try {
            //实例化客户端
            AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
            ////创建API对应的request类
            //AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            //AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            //model.setOutTradeNo(params.get("outTradeNo"));  //商户订单号
            //model.setRefundAmount(params.get("refundAmount"));//退款金额
            //model.setRefundReason(params.get("refundReason"));//退款原因
            //model.setOutRequestNo(params.get("outRequestNo"));//退款请求有号
            //request.setBizModel(model);
            //
            //AlipayTradeRefundResponse response = alipayClient.sdkExecute(request);
            //
            //1ha
            //return response;
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(params.get("outTradeNo")); //与预授权转支付商户订单号相同，代表对该笔交易退款
             model.setRefundAmount(params.get("refundAmount"));
             model.setRefundReason(params.get("refundReason"));
             model.setOutRequestNo(params.get("outRequestNo"));//标识一次退款请求，同一笔交易多次退款需要保证唯一，如部分退款则此参数必传。
             AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
             request.setBizModel(model);
             AlipayTradeRefundResponse response = alipayClient.execute(request);

             return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 验签
     *
     * @param params 参数值
     */
    public static boolean verify(Map<String, String> params) {
        System.out.println("==params======="+params);
        try {
            return AlipaySignature.rsaCheckV1(params, publicKey, charset, signType);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 验签
     *
     * @param request 回调参数
     */
    public static boolean verify(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        System.out.println("==回调的参数"+requestParams);
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // 验签
        return verify(params);
    }
//
//    public static Map<String, String> withhold(){
//        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
//        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
//        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
//        AgreementSignParams agreementSignParams = new AgreementSignParams();
//
//        agreementSignParams.setPersonalProductCode("GENERAL_WITHHOLDING_P");//固定值
//        model.setProductCode("GENERAL_WITHHOLDING");
//        model.setAgreementSignParams(agreementSignParams);
//        SubMerchant subMerchant= new SubMerchant();
//        subMerchant.setMerchantId("2088721060041353");
//        model.setSubMerchant(subMerchant);
//        alipayTradePagePayRequest.setBizModel(model);
//        alipayTradePagePayRequest.setReturnUrl("http://baidu.com");
//        alipayTradePagePayRequest.setNotifyUrl(domain+"/bike/alipay/buyVipByAlipay");
//
//        try {
//            AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(alipayTradePagePayRequest, "get");
//
//            System.out.println("==========="+alipayTradePagePayResponse);
//
//            String orderString = alipayTradePagePayResponse.getBody();// 就是orderString,可以直接给客户端请求，无需再做处理。
//            orderString = URLEncoder.encode(orderString, "UTF-8");
//            Map map = new HashMap();
//            map.put("data",orderString);
//            return  map;
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }


    public static Map<String, String> withhold(String phone)  {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
                AlipayUserAgreementPageSignRequest request = new AlipayUserAgreementPageSignRequest();

        request.setBizContent("{" +
                        "\"product_code\":\"GENERAL_WITHHOLDING\"," +
                        "\"personal_product_code\":\"GENERAL_WITHHOLDING_P\"," +
                        "\"sign_scene\":\"INDUSTRY|CARRENTAL\"," +
                        "\"external_agreement_no\":"+phone+"," +
                        "\"access_params\":{" +
                        "\"channel\":\"ALIPAYAPP\"" +
                        " }," +
                        "\"sub_merchant\":{" +
                        "\"sub_merchant_id\":\"2088721060041353\"," +
                        "\"sub_merchant_name\":\"宁易行\"," +
                        "\"sub_merchant_service_name\":\"宁易行免密支付\"," +
                        "\"sub_merchant_service_description\":\"免密付车费，单次最高500\"" +
                        " }" +
                        " }" );
        request.setNotifyUrl(domain+"/bike/alipay/withholdingResults");
        AlipayUserAgreementPageSignResponse response = null;
        try {
            response = alipayClient.pageExecute(request,"get");
            String orderString= response.getBody();
            orderString = URLEncoder.encode(orderString, "UTF-8");
            Map map = new HashMap();
            map.put("data",orderString);
            return  map;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static AlipayUserAgreementQueryResponse  cx(HttpServletRequest r){
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
                AlipayUserAgreementQueryRequest request = new AlipayUserAgreementQueryRequest();
        request.setBizContent("{" +
                "\"personal_product_code\":"+r.getParameter("personal_product_code")+"," +
                "\"alipay_user_id\":"+r.getParameter("alipay_user_id ")+"," +
                "\"alipay_logon_id\":"+r.getParameter("alipay_logon_id ")+"," +
                "\"sign_scene\":"+r.getParameter("sign_scene ")+"," +
                "\"external_agreement_no\":"+r.getParameter("external_agreement_no")+"," +
                "\"third_party_type\":\"PARTNER\"," +
                "\"agreement_no\":"+r.getParameter("agreement_no")+"" +
                " }");
        AlipayUserAgreementQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            System.out.println(response.getValidTime());;
            System.out.println("===="+response.getBody());
            return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    public static AlipayUserAgreementUnsignResponse rescind(Map map)  {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);

                AlipayUserAgreementUnsignRequest request = new AlipayUserAgreementUnsignRequest();
                request.setBizContent("{" +
                        "\"alipay_logon_id\":"+map.get("alipayLogonId")+"," +
                        "\"personal_product_code\":"+map.get("personalProductCode")+"," +
                        "\"sign_scene\":"+map.get("signScene")+"," +
                        "\"external_agreement_no\":"+map.get("externalAgreementNo")+"," +
                        "\"third_party_type\":"+map.get("thirdPartyType")+"," +
                        "\"agreement_no\":"+map.get("agreementNo")+"," +
                        "\"operate_type\":\"confirm\"" +
                        " }");
        AlipayUserAgreementUnsignResponse response = null;
        try {
            response = alipayClient.execute(request);

            return response;

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
//        if(response.isSuccess()){
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//        }
            return null;
    }



    public static AlipayTradeFastpayRefundQueryResponse returnAmountList(Map map){
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            request.setBizContent("{" +
                    "\"trade_no\":"+map.get("tradeNo")+"," +
                    "\"out_request_no\":"+map.get("outRequestNo")+
                    "  }");
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                return response;
            } else {
                System.out.println("调用失败");
                return null;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }



}
